const vorpal = require('vorpal')()
const Table = require('cli-table')
const Blockchain = require('./block-test')

const blockchain = new Blockchain()

console.log('欢迎来到区块链')

function formatLog(data) {
    if (!Array.isArray(data)) {
        data = [data]
    }
    const first = data[0]
    const head = Object.keys(first)       //取出 对象的key值
    const table = new Table({
        head: head,
        colWidths: new Array(head.length).fill(30)   //限制长度
    })
    const res = data.map(v => {
        return head.map(h => JSON.stringify(v[h], null, 1)) //如果是个对象的话就 转一下格式 并且加一个换行符
    })
    //res 是获取到的对象 name值

    table.push(...res)
    console.log(table.toString());
}

vorpal
    .command('detail <index>', '查看区块详情')
    .action(function (args, callback) {
        const block = blockchain.blockchain[args.index]
        console.log(JSON.stringify(block, null, 2))
    })

vorpal
    .command('blance <address>', '查看余额详情')
    .action(function (args, callback) {
        const blance = blockchain.blance(args.address)
        if (blance) {
            formatLog({ blance, address: args.address })
        }
        callback()
    })



vorpal
    .command('mine', '挖矿')
    .action(function (args, callback) {
        formatLog(blockchain.mine(args.address))
        callback()
    })

vorpal
    .command('chain', '查看区块链')
    .action(function (args, callback) {
        formatLog(blockchain.blockchain)
        callback()
    })
vorpal
    .command('trans <from> <to> <amount>', '转账')
    .action(function (args, callback) {
        let trans = blockchain.transfer(args.from, args.to, args.amount)
        if (trans) {
            formatLog(trans)
        }
        callback()
    })


vorpal.exec('help')
vorpal
    .delimiter("chain=>")
    .show()